package servlet;

import  java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import javax.servlet.*;
import  javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import entity.Goods;

@WebServlet("/selectGoodsByPageServlet")
public class SelectGoodsByPageServlet extends HttpServlet{
    private static final long serialVersionUID=1L;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       Connection con=null;
       PreparedStatement ps=null;
       ResultSet rs=null;
       ArrayList<Goods> allGoods = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try{
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8", "root", "mrt286933605");
            Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
            rs= stmt.executeQuery("select  * from goods");
            //移到最后一行
            rs.last();
            //结果集总数据行
            int totalCount=rs.getRow();
            int totalPage=0;
            //如果没有数据
            if(totalCount==0){
                totalPage=0;//总页数
            }else{
                totalPage=(int)Math.ceil((double) totalCount/3);
            }
            //当前页数
            String pageCurll=request.getParameter("pageCur");
            if(pageCurll==null) {//第一页，赋值1
                pageCurll = "1";
            }
            int pageCur=Integer.parseInt(pageCurll);
            if((pageCur-1)*3>totalCount){
                pageCur=pageCur-1;
            }
            int startIndex=(pageCur-1)*3;
            int perPageSize=3;
            ps=con.prepareStatement("select * from goods limit ? , ?");
            ps.setInt(1,startIndex);
            ps.setInt(2,perPageSize);
            rs=ps.executeQuery();
            allGoods=new ArrayList<Goods>();
            while(rs.next()){
                Goods goods=new Goods();
                goods.setId(rs.getInt(1));
                goods.setGname(rs.getString(2));
                goods.setGprice(rs.getDouble(3));
                allGoods.add(goods);
            }
            request.setAttribute("allGoods",allGoods);
            request.setAttribute("pageCur",pageCur);
            request.setAttribute("totalCount",totalCount);
            request.setAttribute("totalPage",totalPage);
            con.close();
            ps.close();
            rs.close();
        }catch (SQLException e){
            e.printStackTrace();
        }
        //跳转到展示页面
        request.getRequestDispatcher("showGoodsByPage.jsp").forward(request,response);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req,resp);
    }
}
